<?php
require 'vendor/Phpquery/autoload.php';
require 'vendor/Qiniu/autoload.php';

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use QL\QueryList;

ini_set('date.timezone','Asia/Shanghai');

// 用于签名的公钥和私钥
$qiniu_key = '6tlTXdC9jJqqARNW-oaRtDHesA901SWJ3YJXq9Ty';
$qiniu_security = 'TvFPjkNTJA5xKbxokGOFmWalttH7SW0ty-ubTHrc';
// 初始化签权对象
$auth = new Auth($qiniu_key, $qiniu_security);
$bucket = 'guanwang';
// 初始化签权对象
$auth = new \Qiniu\Auth($qiniu_key, $qiniu_security);
$token = $auth->uploadToken($bucket);
$uploadMgr = new UploadManager();
// qiniu end




// 待采集的页面地址
$url = 'https://www.meipian8.cn/1zfhshrd?first_share_uid=8116757&share_depth=2&share_source=groupmessage&share_user_mpuuid=6431afe205ed036af998639bb47ca22d&user_id=ohbsluE1kMplaWWkToXwzoEfzyNI&v=4.10.0';
$url = 'https://www.meipian3.cn/1z86pil8?first_share_uid=2333341&share_depth=8&share_source=timeline&share_user_mpuuid=44aee00b838c2d2656a8d8a5a563b0dd&user_id=ohbsluE1kMplaWWkToXwzoEfzyNI&v=4.10.0';
// 采集规则
$rules = [
    // 文章标题
    'title' => ['.well>h1','text'],
    // 文章内容
    'content' => ['.content-container','html']
];

$data = QueryList::Query($url,$rules)->data;

// $data[0]['content'] 文章内容

//$match_imgs =  'show-img=\".*\"';
//$match_imgs = "/<img.+srcshow-img=\".*\"/";
$match_imgs1 = '/<img.+srcshow-img=\"?(.+)\"?.+>/i';
preg_replace($match_imgs1,'',$data[0]['content']);

print_r($data[0]['content']);exit;

preg_match_all('/<img.+src=\"?(.+)\"?.+>/i',$data[0]['content'],$match);

// https://www.jb51.net/article/134501.htm

//foreach ($match[1] as $v){
//    $data[0]['content']=str_replace($v,'./img/20190322235649.jpg',$data[0]['content']);
//}



print_r($match);exit;



$k=0;
foreach ($match[1] as $v){
    if(!is_dir('./img')){
        mkdir('./img');
    }
    $filename = put_file_img1('./img',$v);
    // default/20181221/c39d6eb438de3ef01c945171593205c4.jpg
    $online_path =  date("Ymd",time());
    $online_path = 'default/'.$online_path;
    // ./img/aa.jpg
    $name_file_arr = explode('/', $filename);
    $tmp_name = $name_file_arr[count($name_file_arr)-1];

    list($ret, $err) = $uploadMgr->putFile($token,$online_path.'/'.$tmp_name, $filename);
    if ($err !== null) {
        var_dump($err);
    } else {
        echo $k++;
        echo  'success!';
    }

    $data[0]['content']=str_replace($v,$filename,$data[0]['content']);

}

/* 抓取保存图片函数
     * return
     * $filename  string  图片地址
     */
function put_file_img($dir='',$image='')
{
    // 判断图片的保存类型 截取后四位地址
    $exts = array('jpeg','png','jpg');
    $filename = $dir.'/'.uniqid().time().rand(10000,99999);
    $imgs = explode('.',$image);
    $ext = $imgs[count($imgs)-1];
    $ext = strstr($ext, '-', true);
    $filename = $filename.'.'.$ext;
//   echo $ext;
    $souce = file_get_contents($image);
    if(file_put_contents($filename,$souce)){
        return $filename;
    }else{
        return false;
    }
}


//print_r($data[0]['content']);
//print_r($match);